package com.summer.campussct.controller;

import com.summer.campussct.pojo.dto.RestResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("file")
public class FileController {

    @Value("${file-position.rootPath}")
    String rootPath;

    @Value("${file-position.tempPath}")
    String tempPath;

    @Value("${file-position.server}")
    String server;


    // todo: 此处替代文件服务器的上传接口，等到搭建文件服务器时再使用其上传接口
    @ApiOperation("图片上传接口")
    @PostMapping(value = "upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public RestResult upload(@RequestPart("file") MultipartFile file) throws IOException {
        String fileOriginalFilename = file.getOriginalFilename();
        int index = fileOriginalFilename.lastIndexOf(".");
        if (index <= 0) return RestResult.error("无效文件");

        String extension =  fileOriginalFilename.substring(index);
        String filename = UUID.randomUUID().toString().replace("-", "") + extension;

        // 存入临时文件夹
        file.transferTo(new File(rootPath + tempPath + filename));
        return RestResult.success( server + "/" + tempPath + filename);
    }
}
